<template>
    <!--  匹配报告-->
    <div style="padding: 10px">
        <div class="report-top">
            <div class="left-section">
                <span style="font-size: 20px; font-weight: bold"
                    >深圳市查策网络信息技术有限公司</span
                >
                <div style="color: #409eff; margin-top: 20px">高企证书编号：GR202344202098</div>
                <div class="border-container">
                    <div class="star-rating">
                        <el-rate v-model="value" allow-half disabled />
                    </div>
                    <!-- 这里是你的内容 -->
                    <div class="info-container">
                        <div class="info-content">
                            <div class="info-label">
                                <div>近一年预计可申报资助（万）</div>
                                <div style="font-size: 50px; color: #e7070f">
                                    {{ sumAmountSubsidyWithCondition }}
                                </div>
                            </div>
                            <div class="info-value">
                                <div>
                                    5星项目数量<span>{{ ratingCounts.five }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="info-container-a">
                        <div class="info-item">
                            总共匹配项目<span>{{ tableData.length }}</span
                            >个
                        </div>
                        <div class="info-item">
                            预计可申报资助总金额<span>{{ sumAmountSubsidy }}</span
                            >万
                        </div>
                    </div>
                    <div id="chart-container" style="width: 430px; height: 400px">
                        <!-- 预计可申报资助图表 -->
                        <echarts1 :subsidyData="subsidyByRatingCount" />
                    </div>
                </div>
            </div>
            <div class="right-section">
                <el-tabs
                    v-model="activeName"
                    class="demo-tabs"
                    @tab-click="handleClick"
                    style="width: 100%"
                >
                    <el-tab-pane label="财务概况" name="first">
                        <finance />
                        <finance1 :staff-structure="staffStructureData" />
                    </el-tab-pane>
                    <el-tab-pane label="财务成长性" name="second">
                        <finance2 />
                        <finance1 :staff-structure="staffStructureData" />
                    </el-tab-pane>
                    <el-tab-pane label="知识产权概况" name="third">
                        <echarts2 />
                        <finance1 :staff-structure="staffStructureData" />
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <div class="report-center">
            <div>
                <div style="font-weight: bold; margin: 20px">匹配政策</div>
                <div
                    class="report-center-echarts"
                    style="display: flex; justify-content: space-between"
                >
                    <!-- 匹配政策图表 -->
                    <echarts3 :counts="ratingCounts" style="width: 600px; height: 200px" />
                    <!-- 政策项目图表 -->
                    <echarts4 :timeData="timeCategoryCounts" style="width: 600px; height: 200px" />
                </div>
            </div>

            <div style="display: flex; justify-content: space-around; margin-top: 50px">
                <!-- 左侧按钮组，没有间隔 -->

                <el-radio-group
                    v-model="selectedLevel"
                    style="margin-bottom: 30px"
                    @change="filterLeftChart"
                >
                    <el-radio-button label="全部">全部</el-radio-button>
                    <el-radio-button label="5星">5星</el-radio-button>
                    <el-radio-button label="4星">4星</el-radio-button>
                    <el-radio-button label="3星">3星</el-radio-button>
                </el-radio-group>

                <!-- 右侧按钮组，带有间隔 -->
                <el-radio-group style="margin-bottom: 30px" @click="filterRightChart">
                    <el-radio-button value="全部">全部</el-radio-button>
                    <el-radio-button value="国家级">国家级</el-radio-button>
                    <el-radio-button value="省级">省级</el-radio-button>
                    <el-radio-button value="市级">市级</el-radio-button>
                    <el-radio-button value="区级">区级</el-radio-button>
                </el-radio-group>
            </div>

            <div style="display: flex" class="zcBox">
                <!-- 图表展示区 -->
                <div class="zhengceBox">
                    <!-- 左侧图表 -->
                    <policy1 :chartData="leftChartData" style="flex: 0 0 48%" />

                    <!-- 右侧图表 -->
                    <RightChart :chartData="rightChartData" style="flex: 0 0 48%" />
                </div>
            </div>
        </div>

        <div class="report-bottom">
            <el-table :data="tableData" border style="width: 100%; margin-top: 20px" stripe>
                <!--                <el-table-column property="index" label="序号" align="center" width="60" />-->
                <el-table-column property="projectName" label="项目名称" align="center" />
                <el-table-column property="acceptanceDepartment" label="受理部门" align="center" />
                <el-table-column property="declarationTime" label="申报时间" align="center" />
                <el-table-column label="匹配度" align="center">
                    <template #default="scope">
                        <el-rate
                            v-model="scope.row.rating"
                            :max="5"
                            :disabled="true"
                            void-color="#c6c6c6"
                            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                        ></el-rate>
                    </template>
                </el-table-column>
                <el-table-column property="amountSubsidy" label="资质额度" align="center" />

                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="primary" :icon="Info" @click="handleDetail(scope.row)"
                            >详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!---------------------- 分页 ---------------------->
            <div class="pagination" style="">
                <el-pagination
                    v-model:current-page="currentPage1"
                    :page-size="100"
                    :size="size"
                    :disabled="disabled"
                    :background="background"
                    layout="total, prev, pager, next"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>

    <project-comp
        :visible="dialogVisible"
        :project="project"
        @update:visible="dialogVisible = $event"
    />
</template>

<script setup lang="ts">
import { type ComponentSize, ElTable } from 'element-plus'
import { ref } from 'vue'
import echarts1 from '../echarts/echarts1.vue'
import echarts2 from '../echarts/echarts2.vue'
import echarts3 from '../echarts/echarts3.vue'
import echarts4 from '../echarts/echarts4.vue'
import finance from '../echarts/finance.vue'

import finance1 from '../echarts/finance1.vue'
import finance2 from '../echarts/finance2.vue'
import policy1 from '../echarts/policy1.vue'
import RightChart from '../echarts/RightChart.vue'
import type { TabsPaneContext } from 'element-plus'

import { detailMatching } from '@/api/customer/customer'
import { detailDetail } from '@/api/detail'

import { useRoute } from 'vue-router'
import ProjectComp from '@/views/client/clientData/matchItem/components/project-comp.vue'

const route = useRoute()

const activeName = ref('first')
const value = ref(5)
const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

const project = reactive({})
const dialogVisible = ref(false)
const handleDetail = (row) => {
    console.log(row)
    getProjectDetail(row)
    dialogVisible.value = true
}

const getProjectDetail = async (row: Record<string, any>) => {
    const data = await detailDetail({
        id: row.id
    })
    setFormData(data)
}
const setFormData = async (data: Record<string, any>) => {
    for (const key in data) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            project[key] = data[key]
        }
    }
}

const tableData = ref([])

const total = tableData.value.length
const currentPage1 = ref(5)

const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

const staffStructureData = ref({})

const staffStructure = () => {
    const total = tableData.value[0].detail.numberOfEmployees // 防止除以0
    console.log('base', total)
    return {
        hrRatio: (((tableData.value[0].detail.hrDevelopmentCount || 0) / total) * 100).toFixed(1),
        doctorRatio: (((tableData.value[0].detail.doctorCount || 0) / total) * 100).toFixed(1),
        abroadRatio: (((tableData.value[0].detail.studyingAbroadCount || 0) / total) * 100).toFixed(
            1
        ),
        seniorTitleRatio: (
            ((tableData.value[0].detail.titleOfASeniorProfessionalPostCount || 0) / total) *
            100
        ).toFixed(1)
    }
}

// 新增响应式变量
const selectedRatings = ref<number[]>([]) // 存储选中的星级
const selectedLevel = ref('全部') // 存储选中的级别
let personalData = ref({})
// const getDetail1 = async () => {

const getDetail1 = async () => {
    const data = await detailMatching({
        id: route.query.id,
        selectedRatings: selectedRatings.value,
        projectName: ''
    })
    // 假设返回的数据结构如下：
    const responseData = data
    console.log('条数1', responseData)
    // 映射返回的数据到 tableData
    if (responseData.length > 0) {
        tableData.value = responseData.map((item) => ({
            id: item.id,
            projectName: item.projectName || '未命名公司',
            rating: item.rating || 0,
            amountSubsidy: item.amountSubsidy,
            acceptanceDepartment: item.acceptanceDepartment,
            declarationTime: item.declarationTime || '未启动',
            ratingFiveCount: item.ratingFiveCount || 0,
            ratingFourCount: item.ratingFourCount || 0,
            ratingThreeCount: item.ratingThreeCount || 0,
            detail: item.detail || {}
        }))
        personalData = tableData.value[0].detail
        console.log('数据1', personalData)
        staffStructureData.value = staffStructure()
    } else {
        tableData.value = []
    }
}

// 受理部门统计
const departmentStats = computed(() => {
    // 使用Map存储统计结果
    const statsMap = new Map<string, { count: number; total: number }>()

    tableData.value.forEach((item) => {
        const department = item.acceptanceDepartment || '未知部门'
        const amount = Number(item.amountSubsidy) || 0

        if (statsMap.has(department)) {
            const existing = statsMap.get(department)!
            existing.count++
            existing.total += amount
        } else {
            statsMap.set(department, { count: 1, total: amount })
        }
    })

    // 转换为数组并排序（按总金额降序）
    return Array.from(statsMap.entries())
        .map(([department, stats]) => ({
            department,
            count: stats.count,
            total: Math.round(stats.total) // 四舍五入取整
        }))
        .sort((a, b) => b.total - a.total)
})

// 计算政策项目数量
const timeCategoryCounts = computed(() => {
    const counts = {
        threeDays: 0, // 三天内
        sevenDays: 0, // 七天内
        fifteenDays: 0, // 15天内
        thirtyDays: 0 // 30天内
    }

    tableData.value.forEach((item) => {
        if (item.declarationTime === '未启动') return

        // 计算日期差
        const targetDate = new Date(item.declarationTime)
        const currentDate = new Date()
        const timeDiff = targetDate.getTime() - currentDate.getTime()
        const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))

        if (dayDiff <= 3) {
            counts.threeDays++
        } else if (dayDiff <= 7) {
            counts.sevenDays++
        } else if (dayDiff <= 15) {
            counts.fifteenDays++
        } else if (dayDiff <= 30) {
            counts.thirtyDays++
        }
    })

    return counts
})

// 计算星级可申报金额
const subsidyByRatingCount = computed(() => {
    return tableData.value.reduce(
        (acc, item) => {
            // 初始化各分类金额
            const categories = {
                fiveStar: 0,
                fourStar: 0,
                threeStar: 0
            }

            // 检查并累加五星
            if (item.ratingFiveCount) {
                categories.fiveStar += item.amountSubsidy || 0
            }

            // 检查并累加四星
            if (item.ratingFourCount) {
                categories.fourStar += item.amountSubsidy || 0
            }

            // 检查并累加三星
            if (item.ratingThreeCount) {
                categories.threeStar += item.amountSubsidy || 0
            }

            // 累加到总结果
            return {
                fiveStar: acc.fiveStar + categories.fiveStar,
                fourStar: acc.fourStar + categories.fourStar,
                threeStar: acc.threeStar + categories.threeStar
            }
        },
        {
            fiveStar: 0,
            fourStar: 0,
            threeStar: 0
        }
    )
})

// 计算政策项目数量
const ratingCounts = computed(() => ({
    five: tableData.value.reduce((s, i) => s + (i.ratingFiveCount || 0), 0),
    four: tableData.value.reduce((s, i) => s + (i.ratingFourCount || 0), 0),
    three: tableData.value.reduce((s, i) => s + (i.ratingThreeCount || 0), 0)
}))

const sumAmountSubsidy = computed(() => {
    return tableData.value.reduce((sum, item) => sum + (item.amountSubsidy || 0), 0)
})

// const sumRatingFiveCount = computed(() => {
//   return tableData.value.reduce((sum, item) => sum + (item.ratingFiveCount || 0), 0)
// })
// const sumRatingFourCount = computed(() => {
//   return tableData.value.reduce((sum, item) => sum + (item.ratingFourCount || 0), 0)
// })
// const sumRatingThreeCount = computed(() => {
//   return tableData.value.reduce((sum, item) => sum + (item.ratingThreeCount || 0), 0)
// })

const sumAmountSubsidyWithCondition = computed(() => {
    return tableData.value.reduce((sum, item) => {
        // 只有当 ratingFiveCount 有值且不等于0时才累加
        if (item.ratingFiveCount && item.ratingFiveCount !== 0) {
            return sum + (item.amountSubsidy || 0)
        }
        return sum
    }, 0)
})

// 左侧柱状图图表数据（受理部门分布）
const leftChartData = computed(() => {
    const topDepartments = departmentStats.value.slice(0, 5) // 取前5个部门

    return {
        departments: topDepartments.map((d) => d.department),
        values: topDepartments.map((d) => d.count), // 数量数据
        amounts: topDepartments.map((d) => d.total) // 金额数据
    }
})
// 右侧图表数据（项目类别分布）
const rightChartData = {
    categories: ['资质认定与奖励', '创新创业', '知识产权', '科研立项', '中小微企业'],
    counts: [10, 20, 5, 25, 15], // 每个类别的数量
    amounts: [100, 200, 150, 300, 150]
}

// 左侧星级筛选方法
const filterLeftChart = (value: string) => {
    const ratingMap: { [key: string]: number[] } = {
        '5星': [5],
        '4星': [4],
        '3星': [3],
        全部: []
    }
    selectedRatings.value = ratingMap[value] || []
    getDetail1()
}

// 右侧按钮点击事件
const filterRightChart = (button: string) => {
    const data = {
        全部: { categories: ['创新创业', '知识产权', '技术转化'], amounts: [100, 200, 150] },
        国家级: { categories: ['创新创业', '知识产权'], amounts: [120, 180] },
        省级: { categories: ['创新创业'], amounts: [50] },
        市级: { categories: ['知识产权', '技术转化'], amounts: [60, 80] },
        区级: { categories: ['技术转化'], amounts: [40] }
    }
    rightChartData.value = data[button]
}

// 默认加载
filterLeftChart('全部')
filterRightChart('全部')

onMounted(() => {
    getDetail1()
})
</script>

<style scoped lang="scss">
/* report-top 容器 */
.report-top {
    width: 100%;
    height: 550px;
    display: flex;
    justify-content: space-between;
    //align-items: center;
    padding: 10px;
    border: 1px solid rgba(167, 167, 167, 0.205);
}

/* 左侧分区 */
.left-section {
    width: 50%;
    padding: 0px 20px;
    /* 边框容器 */

    .border-container {
        position: relative;
        width: 430px;
        /* 设置宽度 */
        height: 130px;
        /* 设置高度 */
        border: 1px solid rgba(167, 167, 167, 0.205);
        box-sizing: border-box;
        /* 星星评分 */

        .star-rating {
            position: absolute;
            top: 15px;
            /* 向上偏移，星星位于边框的外部 */
            right: 10px;
            /* 星星稍微距离右边 */
            font-size: 18px;
        }

        .info-container {
            width: 100%;
            padding: 10px;
            //box-sizing: border-box;
            //border: 1px solid #ccc;
        }

        /* 内容容器，使用 Flexbox 布局 */

        .info-content {
            display: flex;
            /* 使用 Flexbox 布局 */
            justify-content: space-between;
            /* 左右分开对齐 */
            align-items: center;
            /* 垂直居中对齐 */
            padding: 0px 10px;
        }

        .info-label {
            padding-top: 10px;
        }

        /* 数值区域 */

        .info-value {
            margin-top: 50px;

            span {
                color: #e7070f;
                font-size: 40px;
            }
        }

        .info-container-a {
            width: 430px;
            margin-top: 10px;
            padding: 10px 10px;
            background-color: rgba(167, 167, 167, 0.205);
        }

        .info-item {
            color: #8a8a8a;

            span {
                color: #409eff;
            }
        }
    }
}

/* 右侧分区 */
.right-section {
    /* 右侧分区占据可用空间 */
    text-align: right;
    /* 右侧内容右对齐 */
    flex: 1;

    .demo-tabs > .el-tabs__content {
        padding: 32px;
        color: #6b778c;
        font-size: 32px;
        font-weight: 600;
    }
}

.report-center {
    width: 100%;
    margin-top: 20px;
    padding: 20px;
    border: 1px solid rgba(167, 167, 167, 0.205);
}

.report-center-echarts {
    margin-left: 20px;
}

.report-bottom {
    width: 100%;
    height: 620px;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
}

.zcBox {
    overflow: hidden;
}

.zhengceBox {
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;
    gap: 30px;
    margin-top: 20px;
}

.zcBox:hover {
    overflow: auto;
}
</style>
